package com.guaika.reggie.service.impl;

import com.guaika.reggie.common.ResultMessage;
import com.guaika.reggie.common.StringChars;
import com.guaika.reggie.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: reggie_project
 * @ClassName UploadServiceImpl
 * @author: GuaiKa
 * @create: 2022-09-11 20:06
 **/
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    @Value("${reggie.path}")
    private String uploadPath;

    @Override
    public ResultMessage<String> upload(MultipartFile file) {
        log.info("uploadPath: {}", uploadPath);
        //获取上传文件名称
        String originalFilename = file.getOriginalFilename();
        //截取文件类型
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机生成uuid
        String uuid = UUID.randomUUID().toString();
        //判断文件存储路径是否已创建,未创建则创建该文件路径
        File filePath = new File(uploadPath);
        String fileName =  uuid + type;
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            //转存文件
            file.transferTo(new File(uploadPath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return ResultMessage.error(StringChars.UPLOAD_ERROR_MESSAGE.getStr());
        }
        return ResultMessage.success(fileName);
    }

    @Override
    public void download(String name, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            //获取文件输入流
            fileInputStream = new FileInputStream(uploadPath + name);
            //获取文件输出流
            outputStream = response.getOutputStream();
            //设置响应类型
            response.setContentType("image/jpeg");
            //定义数组，加快读取速度
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
